<template>
  <view class="clothes-detail">
    <!-- 图片展示 -->
    <view class="image-container">
      <image 
        :src="clothesDetail.image_url" 
        mode="aspectFit" 
        class="detail-image"
        @click="previewImage"
		@error="handleImageError"
      ></image>
    </view>
    
    <!-- 基本信息 -->
    <view class="info-section">
      <!-- 修改类别展示部分 -->
        <view class="info-item">
          <text class="label">衣服大类:</text>
          <text class="value">{{ clothesDetail.category || '未设置' }}</text>
        </view>
        
        <view class="info-item">
          <text class="label">详细类别:</text>
          <text class="value">{{ clothesDetail.subcategory || '未设置' }}</text>
        </view>
      
      <view class="info-item">
        <text class="label">颜色:</text>
        <text class="value">{{ clothesDetail.color || '未设置' }}</text>
      </view>
      
      <view class="info-item">
        <text class="label">材质:</text>
        <text class="value">{{ clothesDetail.material || '未设置' }}</text>
      </view>
      
      <view class="info-item">
        <text class="label">尺码:</text>
        <text class="value">{{ clothesDetail.size || '未设置' }}</text>
      </view>
      
      <view class="info-item">
        <text class="label">版型:</text>
        <text class="value">{{ clothesDetail.fit || '未设置' }}</text>
      </view>

      <view class="info-item">
        <text class="label">季节:</text>
        <text class="value">{{ clothesDetail.season || '未设置' }}</text>
      </view>      
      
	  <view class="info-item">
	    <text class="label">品牌:</text>
	    <text class="value">{{ clothesDetail.brand || '未设置' }}</text>
	  </view>    
	  
      <view class="info-item">
        <text class="label">闲置天数:</text>
        <text class="value">{{ clothesDetail.days || 0 }}天</text>
      </view>
    </view>
    
    <!-- 标签展示 -->
    <view class="tags-section">
      <text class="section-title">标签</text>
      <view class="tags-container">
        <view 
          v-for="(tag, index) in clothesDetail.tags" 
          :key="index" 
          class="tag"
        >
          <text>{{ tag }}</text>
        </view>
        <view v-if="clothesDetail.tags.length === 0" class="empty-tags">
          <text>暂无标签</text>
        </view>
      </view>
    </view>
    
    <!-- 编辑按钮 -->
    <button class="edit-btn" @click="editClothes">编辑信息</button>
  </view>
</template>
<script>
import setting from "../../setting"
export default {
  data() {
    return {
      clothesDetail: {
        image_url: "",
        mainCategory: "",
        Category: "",
        color: "",
        material: "",
        size: "",
        fit: "",
        season: "",
        brand: "",
        days: 0,
        tags: [],
      },
    }
  },
  onLoad(options) {
    // 优先使用id参数
    if (options.id) {
      this.loadClothesDetail(options.id)
    }
    // 兼容旧的clothesData参数
    else if (options.clothesData) {
      try {
        const data = JSON.parse(options.clothesData)
        this.clothesDetail = data
        // 如果只有clothesData没有id，可以显示警告
        if (!data.clothes_id) {
          console.warn("接收到旧版数据格式，建议更新跳转逻辑")
        }
      } catch (e) {
        console.error("解析衣物数据失败:", e)
      }
    } else {
      uni.showToast({ title: "缺少衣物参数", icon: "none" })
      setTimeout(() => uni.navigateBack(), 1500)
    }
  },
  methods: {
     // 统一图片URL处理方法（与衣柜页面保持一致）
        formatImageUrl(url) {
          if (!url) return ""
          console.log(url);
          // 处理服务器返回的相对路径
          if (url.startsWith('/uploads/')) {
            return `${setting.url}${url}`
          }
          
          // 处理可能存在的其他相对路径
          if (!url.startsWith('http') && !url.startsWith('/static/')) {
            return `${setting.url}/uploads/clothes/${url}`
          }
          
          // 已经是完整URL或静态资源路径
          return url
        },
    // 图片加载失败处理
    handleImageError() {
          this.clothesDetail.image_url = ""
          uni.showToast({
            title: '图片加载失败',
            icon: 'none'
          })
        },
    async loadClothesDetail(clothesId) {
      try {
        uni.showLoading({ title: "加载中...", mask: true })

        const response = await uni.request({
          url: `${setting.url}/api/show_clothes/${clothesId}`,
          method: "GET",
        })

        const [successResponse, failResponse] = Array.isArray(response) ? response : [response, null]
        const res = successResponse || failResponse

        if (res.statusCode === 200 && res.data) {
		 const imageUrl = this.formatImageUrl(res.data.image_url)
          // 计算未使用天数
          const lastUsedDate = res.data.days ? new Date(res.data.days) : null
          const daysDiff = lastUsedDate ? Math.floor((new Date() - lastUsedDate) / (1000 * 60 * 60 * 24)) : null

          this.clothesDetail = {
            ...res.data,
			image_url: imageUrl,
            days: daysDiff, // 存储天数差值
            originalLastUsedDate: res.data.days, // 保留原始日期
            tags: res.data.tags || [],
          }

          console.log("加载成功:", this.clothesDetail)
        } else {
          const errorMsg = res.data?.error || "加载失败"
          uni.showToast({ title: errorMsg, icon: "none" })
        }
      } catch (error) {
        console.error("加载衣物详情异常:", error)
        uni.showToast({ title: "网络异常，请重试", icon: "none" })
      } finally {
        uni.hideLoading()
      }
    },

    editClothes() {
      uni.navigateTo({
        url: `/pages/EditClothes/EditClothes?id=${this.clothesDetail.clothes_id}`,
        events: {
          acceptDataFromEditPage: (data) => {
            this.updateClothesDetail(data)
          },
        },
        success: (res) => {
          res.eventChannel.emit("sendDataToEditPage", this.clothesDetail)
        },
      })
    },

    previewImage() {
        const imageUrl = this.formatImageUrl(this.clothesDetail.image_url)
        if (!imageUrl) return 
        uni.previewImage({
              urls: [imageUrl],
              current: 0
        })
    },
  },
}
</script>
<style scoped>
.clothes-detail {
  padding: 20rpx;
}

.image-container {
  width: 100%;
  height: 400rpx;
  margin-bottom: 30rpx;
}

.detail-image {
  width: 100%;
  height: 100%;
  border-radius: 12rpx;
}

.info-section {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.info-item {
  display: flex;
  padding: 15rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.info-item:last-child {
  border-bottom: none;
}

.label {
  width: 150rpx;
  font-size: 28rpx;
  color: #666;
}

.value {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.tags-section {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 30rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  display: block;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
}

.tag {
  background-color: #f0f0f0;
  border-radius: 8rpx;
  padding: 8rpx 16rpx;
  margin-right: 10rpx;
  margin-bottom: 10rpx;
  font-size: 24rpx;
}

.empty-tags {
  color: #999;
  font-size: 26rpx;
}

.edit-btn {
  margin-top: 40rpx;
  background-color: #FFF200;
  color: black;
  border: 1rpx solid black;
  border-radius: 10rpx;
  font-size: 28rpx;
}
</style>
